﻿/**
as3app - An open-source ActionScript 3.0 Library developed to assist 
in creating simple visual controls/data binding/asset loading for the
Flash player platform.

http://code.google.com/p/as3app/

Copyright (c) 2011 M. K. Chowdhury, All Rights Reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package as3app.appLoader.Assets 
{
	import as3app.core.debug.ILog;
	import as3app.core.debug.logging.LogFactory;
	
	import flash.events.*;
	import flash.display.Loader;
	import flash.net.URLRequest;
	/**
	 * ...
	 * @author Muntasir Kabir Chowdhury
	 */
	public class Asset extends Loader
	{
		private var log:ILog;

		
		
		protected var _batchIDs:Array = new Array();
		public function get BatchIDs():Array { return _batchIDs; }
		
		public function AddToBatchID(batchID:int)
		{
			_batchIDs.push(batchID);
		}
		public function RemoveFromBatchID(batchID:int)
		{
			for (var i:int = 0; i < _batchIDs.length;++i ) 
			{
				if (_batchIDs[i] == batchID) 
				{
					_batchIDs.splice(i, 1);
					return;
				}
			}
		}
		
		
		
		public static const STATUS_IN_PROGRESS:int = 0;
		public static const STATUS_EMPTY:int = 1;
		public static const STATUS_PAUSED:int = 2;
		public static const STATUS_AVAILABLE:int = 3;
		public static const STATUS_ERROR:int = 4;
		
		
		protected var _callBack:Function = null;
		public function get CallBack():Function { return _callBack; }
		public function set CallBack(callBack:Function):void { _callBack = callBack; }
		
		protected var _key:String = "";
		public function get Key():String { return _key; }
		
		protected var _url:String = "";
		protected var _urlReq:URLRequest;
		
		protected var _priority:int = 0;
		public function get Priority():int { return _priority; }
		public function set Priority(priority:int) { _priority = priority; }
		
		
		protected var _isPreFetching:Boolean = false;
		public function get IsPreFetching():Boolean { return _isPreFetching; }
		public function set IsPreFetching(isPreFetching:Boolean) { _isPreFetching=isPreFetching; }
		
		
		protected var _currentStatus:int = STATUS_EMPTY;
		public function get Status():int { return _currentStatus; }
		
		
		
		
		
		protected function SetStatus(status:int):void
		{
			var lastStatus:int = _currentStatus;
			_currentStatus = status;
			if (_callBack != null) 
			{
				_callBack.apply(null, [this, lastStatus]);
			}
		}
		
		
		
		
		private var _errorString:Array = new Array();
		
		
		
		
		
		public function Asset(key:String,url:String,priority:int) 
		{
			log = LogFactory.Register(this);
			
			_key = key;
			_url = url;
			_priority = priority;
			
			// Create Handlers
			this.contentLoaderInfo.addEventListener(Event.COMPLETE, On_LoadingComplete);
			this.contentLoaderInfo.addEventListener(IOErrorEvent.IO_ERROR, On_IOError);
			log.Temp("Asset[" + key + "] : Listeners added");
			
			
			log.Temp("Init : key=" + key + "  url=" + url + "  priority=" + priority.toString());
			
			if (key == null || url == null || priority < 0)
			{
				log.Commit();
				log.Log("Invalid asset information provided. key='" + String(key) + "', url='" + String(url) + "', priority='" + String(priority) + "'");
				SetStatus(STATUS_ERROR);
				return;
			}
			
			
			//this.addEventListener(Event.err, On_LoadingComplete);
			
			
			
				
			try
			{
				_urlReq = new URLRequest(url);
			}
			catch(error:Error)
			{
				log.Commit();
				log.Log("Asset[" + key + "] : Cant initialize '_urlReq' with url = " + _url);
				SetStatus(STATUS_ERROR);
				return;
			}
			
			
			log.Clear();
			log.Log("Asset[" + key + "] : Initialized.");
		}
		
		
		
		
		
		protected function On_LoadingComplete(e:Event)
		{
			log.Log("Asset[" + _key + "] : Load Completed.");
			SetStatus(STATUS_AVAILABLE);
		}
		
		
		
		
		
		protected function On_IOError(e:IOErrorEvent)
		{
			log.Log("Asset[" + _key + "] : Load Error. Event : IOError");
			SetStatus(STATUS_ERROR);
		}
		
		
		
		
		public function Start():void
		{
			
			log.Temp("Asset[" + _key + "] : STARTING...");
			if (_currentStatus==STATUS_EMPTY || _currentStatus==STATUS_PAUSED) 
			{
				log.Temp("Asset[" + _key + "] : Loading will be started...");
				try
				{
					load(_urlReq);
					log.Log("Asset[" + _key + "] : Loading Started.");
					SetStatus(STATUS_IN_PROGRESS);
				}
				catch (error:Error)
				{
					log.Commit();
					log.Log("Asset[" + _key + "] : Error Occured. Stack Trace - " + error.getStackTrace());
					SetStatus(STATUS_ERROR);
				}
				log.Clear();
			}
			
			
		}
		
		
		
		
		
		public function Pause():void
		{
			if (_currentStatus==STATUS_IN_PROGRESS && _batchIDs.length<1)
			{
				log.Temp("Asset[" + _key + "] : Loading will paused...");
				try
				{
					close();
					log.Clear();
					log.Log("Asset[" + _key + "] : Loading paused. Enetering closed state.");
					SetStatus(STATUS_EMPTY);
				}
				catch (error:Error)
				{
					log.Commit();
					log.Log("Asset[" + _key + "] : Error Occured. Stack Trace - " + error.getStackTrace());
					SetStatus(STATUS_ERROR);
				}
				log.Clear();
				
			}
		}
		
		
		
		
		
		
		public function Close():void
		{
			
			if (_currentStatus == STATUS_IN_PROGRESS || _currentStatus == STATUS_PAUSED)
			{
				log.Temp("Asset[" + _key + "] : Close loading...");
				try
				{
					close();
					log.Log("Asset[" + _key + "] : Loading Closed.");
					SetStatus(STATUS_EMPTY);
				}
				catch (error:Error)
				{
					log.Commit();
					log.Log("Asset[" + _key + "] : Error Occured. Stack Trace - " + error.getStackTrace());
					SetStatus(STATUS_ERROR);
				}
				log.Clear();
				
			}
		}	
		
	}

}